//
//  ClothesView.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/27.
//

import SwiftUI

struct ClothesView: View {
    @Environment(\.dismiss) var dismiss
    @ObservedObject var coreVm = CoreDataViewModel.shared
    @StateObject var fileVm = FileManagerViewModel()
    @StateObject var styleVm = ClothStylesViewModel()
    // 存储每个部位的最佳搭配索引
    @State private var bestMatches: [String: [Int]] = [:]
    @State private var maxCounts: [String: Int] = [:]
    @State private var selectedTab = "上装"
    @State private var isAnimatingImage = false
    var id: UUID
    var image: UIImage = UIImage()
    var features: String = ""
    
    var body: some View {
        VStack {
            HStack {
                ButtonView(image: "arrow.left") {
                    dismiss()
                }
                Spacer()
            }
            .overlay(alignment: .center) {
                Text(features)
                    .lineLimit(1)
                    .frame(maxWidth: boundsWidth * 0.5)
                    .font(.system(size: 20, weight: .bold))
            }
            
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .cornerRadius(24)
                .shadow(radius: 8)
                .frame(maxHeight: boundsHeight * 0.25)
                .frame(width: boundsWidth * 0.9)
                .scaleEffect(isAnimatingImage ? 1 : 0.6)
                .padding(.bottom, 10)
            
            TopTabBarView(selectedTab: $selectedTab, tabBarColor: .red)
            
            if let indexs = bestMatches[selectedTab] {
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(spacing: 20) {
                        ForEach(indexs, id: \.self) { index in
                            if let id = coreVm.savedEntities[index].id, let uiImage = fileVm.getImageFromFileManager(id: id), let features = coreVm.savedEntities[index].features {
                                ClothesListCardView(image: uiImage, title: features)
                            }
                        }
                    }
                    .padding(.top)
                }
            } else {
                Spacer()
            }
        }
        .navigationBarBackButtonHidden(true)
        .onAppear {
            let currentFeature = features
            let currentFeatureList = currentFeature.components(separatedBy: "，")
            // 获取当前服装部位
            let currentComponent = Set(clothTypes).intersection(Set(currentFeatureList))
            // 获取厚薄数组，如果为上装下装筛选其中不包含的，用于后续筛选，如果是其他服装类型，数组长度为2用以筛选
            let currentNotThickness = Set(clothThickness).subtracting(Set(currentFeatureList))
            
            var featureList = coreVm.savedEntities.map({ $0.features ?? "" })
            // 将字符串转换为数组
            let featureArrayList = featureList.map({ $0.components(separatedBy: "，") })
            
            // 获取所有可搭配的特征
            let matchingFeatures = findMatchingCombinations(features: currentFeatureList, combinations: styleVm.recommendedCombinations)
            
            for (index, item) in featureArrayList.enumerated() {
                // 上装与上装不能搭配，同时也会过滤掉自身
                if Set(item).isDisjoint(with: currentComponent) {
                    // 筛选厚度，如果厚度不同就不能搭
                    if currentNotThickness.count == 1 && item.contains(currentNotThickness) {
                        continue
                    }
                    for component in clothTypes {
                        if item.contains(component) {
                            let matchCount = findMatchingCount(features: item, combinations: matchingFeatures)
                            if matchCount > maxCounts[component] ?? 0 {
                                maxCounts[component] = matchCount
                                bestMatches[component] = [index]
                            } else if matchCount == maxCounts[component] && maxCounts[component] != 0 {
                                bestMatches[component]?.append(index)
                            }
                        }
                    }
                }
            }
            withAnimation(.easeOut(duration: 0.5)) {
                isAnimatingImage = true
            }
        }
        .onDisappear {
            // 清空数据，避免在MineView出现下标越界的错误
            bestMatches = [:]
            maxCounts = [:]
        }
    }
}

#Preview {
    ClothesView(id: UUID())
}
